import { AxiosRequestConfig, AxiosPromise, AxiosResponse } from './types'
import xhr from './xhr'
import { buildURL } from './helpers/url'
import { tranformRequest, tranformResponse } from './helpers/data'
import { processHeader } from './helpers/header'

function axios(config: AxiosRequestConfig): AxiosPromise {
  processConfig(config)
  return xhr(config).then((res: AxiosResponse) => {
    return tranformResponseData(res)
  })
}

function processConfig(config: AxiosRequestConfig): void {
  config.url = transformURL(config)
  config.headers = tranformHeader(config)
  config.data = tranformRequestData(config)
}

function transformURL(config: AxiosRequestConfig): string {
  let { url, params } = config

  return buildURL(url, params)
}

function tranformRequestData(config: AxiosRequestConfig): any {
  return tranformRequest(config.data)
}

function tranformHeader(config: AxiosRequestConfig): any {
  const { headers = {}, data } = config

  return processHeader(headers, data)
}

function tranformResponseData(res: AxiosResponse): any {
  res.data = tranformResponse(res.data)

  return res
}

export default axios
